package com.itheima.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.Bean.*;
import com.itheima.Dao.OrderDetailsDao;
import com.itheima.Dao.OrdersDao;
import com.itheima.Service.*;
import com.itheima.common.BaseContext;
import com.itheima.exception.CustomException;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;


    @Override
    @Transactional
    public void submit(Orders orders) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
        //查询用户数据
        User user = userService.getById(userId);
        if(user==null){
            throw new CustomException("该用户不存在！");
        }
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);

        if(shoppingCartList.isEmpty()){
            throw new CustomException("购物车为空，不能下单");
        }

        long orderId = IdWorker.getId();//订单号

        BigDecimal sumAmount = new BigDecimal(0);
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail,"id");
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
            sumAmount = sumAmount.add(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())));
        }

        //组装订单数据
        orders.setId(orderId);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(sumAmount);//总金额
        //查询地址数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetailList);

        //向订单表插入数据，一条数据
        this.save(orders);

        //清空购物车数据
        shoppingCartService.remove(lqw);

    }
}
